package org.springframework.boot.netty.viewResolver;

import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.netty.NettyProperties;
import org.springframework.boot.netty.support.ModelAndView;
import org.springframework.boot.netty.view.View;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Author: huoxingzhi
 * Date: 2020/12/28
 * Email: hxz_798561819@163.com
 */
public class ViewResolverComposite implements ViewResolver {

    private NettyProperties nettyProperties;

    List<ViewResolver> viewResolvers = new LinkedList<>();

    @Override
    public View resolveViewName(ModelAndView modelAndView) throws Exception {

        View view = null;
        for (ViewResolver viewResolver : viewResolvers) {
            view = viewResolver.resolveViewName(modelAndView);
            if(null!=view){
                break;
            }
        }

        return view;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.nettyProperties = applicationContext.getBean(NettyProperties.class);

        Arrays.stream(applicationContext.getBeanNamesForType(ViewResolver.class)).forEach(viewResolverName ->{
            this.viewResolvers.add(applicationContext.getBean(viewResolverName,ViewResolver.class));
        });

        // ViewResolver 排序
        AnnotationAwareOrderComparator.sort(this.viewResolvers);
    }
}
